//
//  NewFeature.swift
//  新浪微博
//
//  Created by MBP on 16/5/16.
//  Copyright © 2016年 MBP. All rights reserved.
//

import UIKit
import SnapKit

/// 新特性图像数量
private let PNNewFeatureImageCount = 4

class NewFeature: UIView {

    //构造函数
    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
        
        //设置视图
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        print("\(classForCoder)\(#function)")
    }
    

    // MARK: - 私有属性
    /// 分页控件
    private lazy var pageControl = UIPageControl()

}

extension NewFeature {
    private func setupUI() {
        //创建UIScrollView
        let scrollView = UIScrollView(frame: bounds)
        //加入到新特性VC
        addSubview(scrollView)
        //给scrollView 添加图像
        for i in 0..<PNNewFeatureImageCount {
            let  imageName = "new_feature_\(i + 1)"
            let imageView = UIImageView(pn_imageName: imageName)

            scrollView.addSubview(imageView)
            //设置frame
            imageView.frame = CGRectOffset(bounds, CGFloat(i) * bounds.width, 0)
        }
        
        //设置scrollView内容大小
        scrollView.contentSize = CGSize(width: bounds.width * CGFloat(PNNewFeatureImageCount + 1), height: 0)
        
        //取消弹簧效果、滚动条, 打开分页显示内容
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.pagingEnabled = true
        
        //添加分页控件
        addSubview(pageControl)
        
        pageControl.hidesForSinglePage = true
        pageControl.numberOfPages = PNNewFeatureImageCount
        pageControl.currentPage = 0
        pageControl.pageIndicatorTintColor = UIColor.blackColor()
        pageControl.currentPageIndicatorTintColor = PNAppearanceTintColor
        // 禁用交互
        pageControl.userInteractionEnabled = false
        
        //自动布局
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-80)
        }
        
        //设置代理
        scrollView.delegate = self
    }
}


//scrollView 代理方法
extension NewFeature: UIScrollViewDelegate {
    //滚动减速完成
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //计算当前页面
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        //如果是最后一页, 则销毁scrollView
        if page == PNNewFeatureImageCount {
            removeFromSuperview()
        }
    }
    
    //发生滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //计算页码
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        //使分页控件正确显示当前页码
        pageControl.currentPage = page
        
        //如果是最后一页, 则不显示分页控件
        if page == PNNewFeatureImageCount {
            pageControl.hidden = true
        }else {
            pageControl.hidden = false
        }
    }
}
